/* Copyright (c) 2016-2020 Enfry Ltd. All Rights Reserved.
 * 
 * This software is the confidential and proprietary information of Enfry. 
 * You shall not disclose such Confidential Information
 * and shall use it only in accordance with the terms of the agreements
 * you entered into with Enfry.
 */
package com.enfry.common.util.httpclient;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;

import com.enfry.common.util.Files;
import com.enfry.common.util.Streams;
import com.enfry.common.util.validate.Validates;

/**
 * 
 * 下载工具类
 * 
 * @Title com.enfry.util.httpclient.HttpResult
 * @author Penghu
 * @date 2018年2月28日
 */
public class HttpDownload extends HttpClient {
	private String fileDir;
	private String fileName;
	private File file;

	public HttpDownload(String url) {
		super(url, _GET_);
	}

	public void setFileDir(String fileDir) {
		this.fileDir = fileDir;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public String getFileDir() {
		return fileDir;
	}

	public File getFile() {
		return file;
	}

	public String getFileName() {
		return fileName;
	}

	protected boolean doPreRequestProperty() {
		if (Files.exists(fileDir)) {
			if (!Files.isDirectory(fileDir)) {
				responseStatus = _72_PARAM_NOT_SATISFIED_;
				responseText = "请求的文件存放目录不正确";
				return false;
			}
		} else {
			if (!Files.mkDirectory(fileDir)) {
				responseStatus = _72_PARAM_NOT_SATISFIED_;
				responseText = "请求的文件存放目录不正确";
				return false;
			}
		}

		// 如果没有指定类型，则设置支持全部类型
		if (!hasRequestProperty("Accept"))
			addRequestProperty("Accept", "*/*");

		return true;
	}

	protected void doReadResponseContent(HttpURLConnection conn) throws IOException {
		if (responseStatus == _302_FOUND_) {// 重定向
			responseText = conn.getHeaderField("Location");
			return;
		}

		if (responseStatus != _200_OK_) {// 错误
			responseText = "调用服务端接口失败，错误码：" + responseStatus;
			return;
		}

		// 成功，获取文件名，如果用户未指定文件名则取连接中是否有文件名
		if (Validates.isEmpty(fileName))
			fileName = getFileName(conn);

		if (Validates.isEmpty(fileName)) {// 如果未指定且连接属性中没有则查看URL中有没有，判断方法是看有没有2-5位后缀
			String fileExt = Files.getFileExt(url);
			if (Validates.isAlphabeticLen(fileExt, 2, 5))
				fileName = Files.getFileName(url, "/");
		}

		if (Validates.isEmpty(fileName)) {// 未配置、连接属性中没有、URL没有则报错
			responseStatus = _72_PARAM_NOT_SATISFIED_;
			responseText = "未指定文件名称";
			return;
		}

		file = new File(fileDir, fileName);
		FileOutputStream output = new FileOutputStream(file);
		Streams.putBytes(conn.getInputStream(), output);
		output.close();
		responseText = "下载成功";
	}
}
